import {
  Button,
  Card,
  Col,
  Form,
  Input,
  InputNumber,
  Modal,
  Row,
  Space,
  Popconfirm,
  Select,
} from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import { useEffect, useState } from 'react';

import commonService from '@/api/services/commonService';
import { useCommon } from '@/hooks/common';
import { toFen, toYuan } from '@/utils/format-number';

import DetailModal from './detail';

const payTypeMap: any = {
  1: '微信',
  2: '支付宝',
  3: 'paypal',
  4: '余额',
  5: '线下支付',
  6: '平台奖励',
  7: '提现驳回',
};

const sendTypeMap: any = {
  1: '申通快递',
  2: 'China Post Registered Air Mail',
  3: '圆通快递',
  4: '顺风快递',
  5: 'DHL',
  8: 'Epacket',
  9: '上门自提',
};

const statusMap: any = {
  0: '待付款',
  1: '待发货',
  8: '待收货',
  9: '已关闭',
};

const statusOptions = Object.keys(statusMap).map((key) => {
  return { label: statusMap[key], value: key };
});

export default function OrderPage() {
  const uri = 'order';
  const cateName = '订单管理';
  const {
    data = {},
    ModalPros,
    searchForm,
    onSearchFormReset,
    onEdit,
    onSearch,
    handleChange,
    refetch,
  } = useCommon({ orderNumber: '', userId: '', status: '' }, uri, {
    loginName: '',
    id: 0,
    userName: '',
    userType: '',
    phoneNumber: '',
  });

  const [showDetail, setShowDetail] = useState(false);
  const [detail, setDetail] = useState<any>({});

  const doClose = (id: string) => {
    commonService.postCustomApi(`/admin/order/closeOrder?orderId=${id}`, {}).then((res) => {
      refetch();
    });
  };

  const toDetail = (orderNumber: string) => {
    commonService.getCustomApi('/admin/order/orderDetail', { orderNumber }).then((res) => {
      setDetail(res);
      setShowDetail(true);
    });
  };

  const columns: ColumnsType<any> = [
    { title: '订单编号', dataIndex: 'orderNumber', align: 'center', width: 120 },
    { title: '会员ID', dataIndex: 'userId', align: 'center', width: 60 },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 120,
      render: (status) => <div>{statusMap[status]}</div>,
    },
    {
      title: '付款方式',
      dataIndex: 'payType',
      align: 'center',
      width: 120,
      render: (payType) => <div>{payTypeMap[payType]}</div>,
    },
    {
      title: '订单金额',
      dataIndex: 'totalPrice',
      align: 'center',
      width: 140,
      render: (_, row) => {
        return <div className="flex flex-col">
            <div>平台原价：{toYuan(row.totalPrice)}</div>
            <div>优惠券金额：{toYuan(row.couponMoney)}</div>
            <div>优惠后金额：{toYuan(row.price)}</div>
            <b>最终价格：{toYuan(row.finalPrice)}</b>
            <div>（运费：{toYuan(row.freight)}）</div>
          </div>;
      },
    },
    { title: '下单时间', dataIndex: 'createTime', align: 'center', width: 200 },
    {
      title: '运费',
      dataIndex: 'freight',
      align: 'center',
      width: 120,
      render: (freight) => <div>{toYuan(freight)}</div>,
    },
    {
      title: '发货方式',
      dataIndex: 'sendType',
      align: 'center',
      width: 80,
      render: (sendType) => <div>{sendTypeMap[sendType]}</div>,
    },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 100,
      fixed: 'right',
      render: (_, record) => (
        <div className="flex flex-col gap-[10px] w-full justify-center text-gray">
          {record.status === 0 ? <><Popconfirm
            title="确认删除该数据？"
            okText="确定"
            cancelText="取消"
            placement="left"
            onConfirm={() => doClose(record.id)}
          >
            <Button>关闭订单</Button>
          </Popconfirm>
          <Button onClick={() => onEdit(record)}>修改价格</Button></> : ''}
          <Button onClick={() => toDetail(record.orderNumber)}>订单详情</Button>
        </div>
      ),
    },
  ];

  // rowSelection objects indicates the need for row selection
  const rowSelection: TableRowSelection<any> = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows);
    },
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      <Card>
        <Form form={searchForm} onFinish={onSearch}>
          <Row gutter={[16, 16]}>
            <Col span={8} lg={6}>
              <Form.Item<any> label="订单编号" name="orderNumber" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="会员ID" name="userId" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="订单状态" name="status" className="!mb-0">
                <Select options={statusOptions} />
              </Form.Item>
            </Col>
            <Col span={24} lg={12}>
              <div className="flex justify-end">
                <Button onClick={onSearchFormReset}>重置</Button>
                <Button type="primary" htmlType="submit" className="ml-4">
                  查询
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card
        title={cateName}
        extra={
          <div className="flex flex-row gap-[10px]">
            {/* <Button
              type="primary"
              onClick={() =>
                onCreate({ parentId: query.parentId, level: query.parentId === 0 ? 1 : 2 })
              }
            >
              新增
            </Button> */}
          </div>
        }
      >
        <Table
          rowKey="id"
          size="small"
          pagination={{ total: data.totalCount }}
          scroll={{ x: 'max-content' }}
          columns={columns}
          dataSource={data.list}
          rowSelection={{ ...rowSelection }}
          onChange={handleChange}
        />
      </Card>

      <CommonModal {...ModalPros} />
      <DetailModal onOk={() => setShowDetail(false)} onCancel={() => setShowDetail(false)} showDetail={showDetail} detail={detail} />
    </Space>
  );
}

function CommonModal({ title, show, formValue, onOk, onCancel }: any) {
  const [form] = Form.useForm();
  useEffect(() => {
    form.setFieldsValue({ ...formValue, finalPrice: toYuan(formValue.finalPrice) });
  }, [formValue, form]);

  const handleOk = () => {
    const params = { ...formValue, ...form.getFieldsValue() };
    params.finalPrice = toFen(params.finalPrice);
    onOk(params);
  };
  return (
    <Modal
      title={title}
      open={show}
      onOk={() => handleOk()}
      onCancel={onCancel}
    >
      <Form
        initialValues={formValue}
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        layout="horizontal"
      >
        <Form.Item<any> label="价格" name="finalPrice" required>
          <InputNumber suffix="元" />
        </Form.Item>
      </Form>
    </Modal>
  );
}
